import uuid
from datetime import datetime
from typing import Optional, List
from enum import Enum as PyEnum
from pydantic import BaseModel, Field
from sqlalchemy import Column, BigInteger, String, Integer, SmallInteger, Date, DateTime, Enum, text, Numeric, Index, \
    ForeignKey
from core.database import Base


class CustomerSourceEnum(str, PyEnum):
    """
    客户来源枚举
    """
    ONLINE_PROMOTION = "online_promotion"  # 线上推广
    REFERRAL = "referral"                  # 推荐
    DOUYIN = "douyin"                     # 抖音
    SMS = "sms"                  # 短信
    WORK_WECHAT = "work_wechat"          # 企微
    EXHIBITION = "exhibition"              # 展会
    ADVERTISEMENT = "advertisement"        # 广告
    OTHER = "other"


class ListTypeEnum(str, PyEnum):
    RESOURCE = "resource"
    FOLLOWING = "following"  # 我跟进的客户
    ASSISTING = "assisting"  # 我协助的客户
    SCHEDULED = "scheduled"  # 预约上门客户


class Customers(Base):
    __tablename__ = 'customers'
    # 主键
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment='主键ID')
    # 客户编号
    customer_id = Column(String(36), unique=True, nullable=False,default=lambda: str(uuid.uuid4()), comment='客户唯一编号')
    user_id = Column(String(36), comment='用户id')
    # 基本信息
    customer_name = Column(String(100), nullable=False, comment='客户名称')
    type = Column(SmallInteger, nullable=False, default=1, comment='客户类型：1=潜在 2=意向 3=需求 4=签单 5=放款')
    email = Column(String(100), unique=True, comment='邮箱')
    phone = Column(String(20), unique=True, comment='手机号')
    avatar = Column(String(255), comment='头像URL')
    address = Column(String(255), comment='详细地址')
    city = Column(String(128), comment='城市')
    age = Column(Integer, comment='年龄')  # 新增年龄字段
    tags = Column(String(255), comment='标签')
    source = Column(String(255), comment='来源')
    customer_level = Column(String(8), comment='客户等级')
    # 期望金额字段（单位：万元）
    expected_amount = Column(Numeric(15, 2), comment='期望金额（单位：万元）')
    customer_situation = Column(String(512), comment='客户情况')
    company_name = Column(String(256), comment='企业名')
    #助贷阶段
    assist_stage = Column(String(255), comment='助贷阶段("沟通"/"到店")')
    #营销员id
    salesman_id = Column(String(36), comment='营销员id')
    # 个人信息
    gender = Column(String(10), comment='性别')
    id_card = Column(String(18), comment='身份证号')

    external_id = Column(String(64), comment='外部id')
    # ... 其他字段 ...
    current_task_id = Column(String(36), comment='当前任务id')
    # 状态信息
    status = Column(SmallInteger, nullable=False, default=1, comment='状态：1-正常，0-禁用')
    #被轮呼的次数
    called_count = Column(Integer, nullable=False, default=0, comment='被轮呼的次数')
    # 新增客户状态字段
    list_type = Column(String(18), default=ListTypeEnum.RESOURCE.value, comment='客户状态')

    in_call_task = Column(SmallInteger, nullable=False, default=0, comment='是否在呼叫任务中 0-未在轮呼任务 1-在轮呼任务')
    sms_status = Column(String(18), comment='短信状态')

    # 时间
    created_at = Column(DateTime, default=datetime.now, server_default=text('CURRENT_TIMESTAMP'), comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now,
                        server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间')

    follow_number = Column(String(20), comment='跟进手机号手机号')

    # 添加索引
    __table_args__ = (
        Index('idx_customer_id', 'customer_id'),
        Index('idx_phone', 'phone'),
        Index('idx_customer_name', 'customer_name'),
    )

    def __repr__(self):
        return f"<Customer(id={self.id}, name='{self.customer_name}', email='{self.email}')>"

    def to_dict(self):
        # 将模型转换为字典，便于JSON序列化
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class CustomerPlatformUpdate(BaseModel):
    phone: str
    platform: str
    status: str


class CustomerCreate(BaseModel):
    """
    用于创建新客户的 Pydantic 模型
    """
    # 基本信息
    customer_name: Optional[str] = Field(None, max_length=100, description="客户名称")
    type: int = Field(default=1, ge=1, le=5, description="客户类型：1=潜在 2=意向 3=需求 4=签单 5=放款")
    email: Optional[str] = Field(None, max_length=100, description="邮箱")
    phone: Optional[str] = Field(None, max_length=20, description="手机号")
    avatar: Optional[str] = Field(None, max_length=255, description="头像URL")
    address: Optional[str] = Field(None, max_length=255, description="详细地址")
    city: Optional[str] = Field(None, max_length=128, description="城市")
    age: Optional[int] = Field(None, ge=0, le=150, description="年龄")
    tags: Optional[str] = Field(None, max_length=255, description="标签")
    source: Optional[str] = Field(None, max_length=255, description="来源")
    customer_level: Optional[str] = Field(None, max_length=8, description="客户等级")
    external_id: Optional[str] = Field(None, max_length=64, description="外部id")
    # 期望金额字段（单位：万元）
    expected_amount: Optional[float] = Field(None, ge=0, description="期望金额（单位：万元）")
    customer_situation: Optional[str] = Field(None, max_length=512, description="客户情况")
    company_name: Optional[str] = Field(None, max_length=256, description="企业名")
    # 助贷阶段
    assist_stage :Optional[str] = Field(None, max_length=256, description="助贷阶段(沟通到店)")
    # 营销员id
    salesman_id :Optional[str] = Field(None, max_length=256, description="营销员id")
    # 个人信息
    gender: Optional[str] = Field(None, max_length=10, description="性别")
    id_card: Optional[str] = Field(None, max_length=18, description="身份证号")
    sms_status : Optional[str] = Field(None, max_length=18, description="短信状态")
    # 跟进手机号
    follow_number: Optional[str] = Field(None, max_length=20, description="跟进手机号")
    # 状态信息
    status: int = Field(default=1, ge=0, le=1, description="状态：1-正常，0-禁用")
    call_status: int = Field(default=1, ge=1, le=4, description='呼叫状态：1-未轮呼 2-轮呼中 3-已接通 4-未接通')


class H5CustomerCreate(BaseModel):
    """
    用于H5端创建/更新客户的 Pydantic 模型
    """
    customer_name: str = Field(..., max_length=100, description="客户名称")
    phone: str = Field(..., max_length=20, description="手机号")
    customer_situation: Optional[str] = Field(None, max_length=512, description="客户情况/备注")
    follow_number: Optional[str] = Field(None, max_length=20, description="跟进手机号")


class ChatMessageCreate(BaseModel):
    """
    用于创建聊天记录的 Pydantic 模型
    """
    session_id: str = Field(..., description="会话ID")
    sender: str = Field(..., description="发送者")
    receiver: str = Field(..., description="接收者")
    content: str = Field(..., description="聊天内容")


class CustomerUpdate(BaseModel):
    """
    用于更新客户信息的 Pydantic 模型
    """
    customer_id: str = Field(..., description="客户ID")
    # 基本信息
    customer_name: Optional[str] = Field(None, max_length=100, description="客户名称")
    type: Optional[int] = Field(None, ge=1, le=5, description="客户类型：1=潜在 2=意向 3=需求 4=签单 5=放款")
    email: Optional[str] = Field(None, max_length=100, description="邮箱")
    phone: Optional[str] = Field(None, max_length=20, description="手机号")
    avatar: Optional[str] = Field(None, max_length=255, description="头像URL")
    address: Optional[str] = Field(None, max_length=255, description="详细地址")
    city: Optional[str] = Field(None, max_length=128, description="城市")
    age: Optional[int] = Field(None, ge=0, le=150, description="年龄")
    tags: Optional[str] = Field(None, max_length=255, description="标签")
    source: Optional[str] = Field(None, max_length=255, description="来源")
    customer_level: Optional[str] = Field(None, max_length=8, description="客户等级")
    external_id: Optional[str] = Field(None, max_length=64, description="外部id")
    # 期望金额字段（单位：万元）
    expected_amount: Optional[float] = Field(None, ge=0, description="期望金额（单位：万元）")
    customer_situation: Optional[str] = Field(None, max_length=512, description="客户情况")
    company_name: Optional[str] = Field(None, max_length=256, description="企业名")
    # 助贷阶段
    assist_stage: Optional[str] = Field(None, max_length=256, description="助贷阶段(沟通到店)")
    # 营销员id
    salesman_id: Optional[str] = Field(None, max_length=256, description="营销员id")
    # 个人信息
    gender: Optional[str] = Field(None, max_length=10, description="性别")
    id_card: Optional[str] = Field(None, max_length=18, description="身份证号")
    sms_status: Optional[str] = Field(None, max_length=18, description="短信状态")
    # 跟进手机号
    follow_number: Optional[str] = Field(None, max_length=20, description="跟进手机号")
    # 状态信息
    status: Optional[int] = Field(None, ge=0, le=1, description="状态：1-正常，0-禁用")
    call_status: Optional[int] = Field(None, ge=1, le=4, description='呼叫状态：1-未轮呼 2-轮呼中 3-已接通 4-未接通')


class BatchCreateCustomerItem(BaseModel):
    """
    用于批量创建客户的 Pydantic 模型
    """
    # 基本信息
    customer_name: str = Field(..., max_length=100, description="客户名称")
    type: int = Field(default=1, ge=1, le=5, description="客户类型：1=潜在 2=意向 3=需求 4=签单 5=放款")
    email: Optional[str] = Field(None, max_length=100, description="邮箱")
    phone: str = Field(..., max_length=20, description="手机号")
    avatar: Optional[str] = Field(None, max_length=255, description="头像URL")
    address: Optional[str] = Field(None, max_length=255, description="详细地址")
    city: Optional[str] = Field(None, max_length=128, description="城市")
    age: Optional[int] = Field(None, ge=0, le=150, description="年龄")
    tags: Optional[str] = Field(None, max_length=255, description="标签")
    source: Optional[str] = Field(None, max_length=255, description="来源")
    customer_level: Optional[str] = Field(None, max_length=8, description="客户等级")
    external_id: Optional[str] = Field(None, max_length=64, description="外部id")
    # 期望金额字段（单位：万元）
    expected_amount: Optional[float] = Field(None, ge=0, description="期望金额（单位：万元）")
    customer_situation: Optional[str] = Field(None, max_length=512, description="客户情况")
    company_name: Optional[str] = Field(None, max_length=256, description="企业名")
    # 助贷阶段
    assist_stage: Optional[str] = Field(None, max_length=256, description="助贷阶段(沟通到店)")
    # 营销员id
    salesman_id: Optional[str] = Field(None, max_length=256, description="营销员id")
    # 个人信息
    gender: Optional[str] = Field(None, max_length=10, description="性别")
    id_card: Optional[str] = Field(None, max_length=18, description="身份证号")
    sms_status: Optional[str] = Field(None, max_length=18, description="短信状态")
    # 跟进手机号
    follow_number: Optional[str] = Field(None, max_length=20, description="跟进手机号")
    # 状态信息
    status: int = Field(default=1, ge=0, le=1, description="状态：1-正常，0-禁用")
    call_status: int = Field(default=1, ge=1, le=4, description='呼叫状态：1-未轮呼 2-轮呼中 3-已接通 4-未接通')


class BatchCreateCustomersRequest(BaseModel):
    """
    批量创建客户请求模型
    """
    customers: List[BatchCreateCustomerItem] = Field(..., description="客户列表")
    channel:  str = Field(..., description="通道")